// pages/shop/erji//orderQr/orderQrPt.js
var base = require('../../../../base.js');  //路径可能做相应调整
const _ = base._; //翻译函数
const PAGES = require('../../../../utils/pages.js')
const { timePeisZh, timestampToYMD, timePeisStartMin } = require('../../../../utils/util.js')
const { getUserToken, getUserInfo } = require('../../../../lib/user.js')
const { URL } = require('../../../../lib/urls.js')
const { HTTP } = require('../../../../lib/http.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: [],
    usageModel: 0,//0 外卖/配送，1 堂食，2 自取
    otherData: [
      {
        colorbg: "FFC0CB",
        colortxt: "DB7093",
        tagName: "商品金额",
        otherName: "商品小计",
        money: 0,
      },
      {
        colorbg: "dddddd",
        colortxt: "333333",
        tagName: "包装费",
        otherName: "产品包装",
        money: 0,
      }, {
        colorbg: "87CEFA",
        colortxt: "00BFFF",
        tagName: "配送费",
        otherName: "专车专送",
        money: 0,
      },
    ],
    goodsList: [],
    remarkCon: _("设置备注"),//订单备注
    companyName: _("设置发票"),//发票信息
    //到店时间内容
    minHour: 10,
    maxHour: 20,
    minDate: timePeisStartMin(),
    maxDate: new Date(2021, 10, 1).getTime(),
    ddsjCurrentDate: timestampToYMD(timePeisStartMin(), "Y/M/D h:m"),
    showDDSJ: false,
    // 到店人数
    ddrsColumns: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'],
    ddrsValue: "1",
    showDDrs: false,
    // // 配送方
    // showPSF: false,
    // psDwColumns: [],
    // psDwValueColumns: [],
    // psDwValue: "",
    // psDwCode: "",
    // 送出时间
    showSCSJ: false,
    sctimeColumns: [],
    sctimeWzColumns: [],
    SCSJWZValue: timestampToYMD(timePeisStartMin(), "Y-M-D h:m:s"),
    pssjminDate: timePeisStartMin(),
    SCSJValue: timestampToYMD(timePeisStartMin(), "M月D日 h:m"),
    pssjmaxDate: new Date().getTime() + 7 * 24 * 3600 * 1000,
    pscurrentDate: timePeisStartMin(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      } else if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    filter(type, options) {
      if (type === 'minute') {
        return options.filter(option => option % 10 === 0)
      }
      return options;
    },
    //订单总金额
    totalPrice: 0,
    couponPrice: 0,
    productCode: "",
    productCount: 0,
    addressInfo: null,
    couponCode: "",
    storeInfo: null,//默认门店
    fapiaoModel: null,
    deliveryMethod: 0,
    deliveryMethodArray:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      _t: base._t(), //翻译
    });
    var item = JSON.parse(decodeURIComponent(options.data));
    this.setData({
      goodsList: item,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //设置配送时间
    // this.setPsTime();
    // this.getNetDeliveryList();//获取配送方式
    // this.getNetDefAddressList();//获取默认收获地址
    this.getNetDefStoreList();//获取默认门店
  },
  setPsTime: function () {
    //设置配送时间
    var timeList = ["立即送出"];
    var timestamp = Date.parse(new Date());
    for (var i = 1; i < 24; i++) {
      timeList.push(timePeisZh(timestamp + i * 3600 * 1000));
    }
    this.setData({
      sctimeColumns: timeList,
      SCSJValue: timeList[0]
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (this.data.fapiaoModel) {
      this.setData({
        companyName: that.data.fapiaoModel.CompanyName
      })
    } else {
      this.setData({
        companyName: _("设置发票")
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 切换商品使用方式
   */
  changUsageModel: function (e) {
    let type = e.currentTarget.dataset.type;//切换单选按钮
    this.setData({
      usageModel: type,
    })
  },

  // 设置备注
  changRemarkTap: function () {
    var that = this;
    var remark = that.data.remarkCon == _("设置备注") ? "" : that.data.remarkCon
    wx.navigateTo({
      url: PAGES.orderQrRemark + '?remark=' + remark
    })
  },
  // 设置发票
  changFapiaoTap: function () {
    var that = this;
    wx.navigateTo({
      url: PAGES.fapiaoSelect
    })
  },
  //设置收货地址
  changShAddress: function () {
    //type: 1选择收获地址
    wx.navigateTo({
      url: PAGES.myAddress
    })
  },
  //选择优惠券
  changCouponTap: function () {
    //type: 1选择收获地址
    wx.navigateTo({
      url: PAGES.selectCoupon
    })
  },
  //选择门店
  changMd: function () {
    //type: 1选择收获地址
    wx.navigateTo({
      url: PAGES.selectMendian + '?productCode=' + this.data.productCode
    })
  },
  // 到店人数编辑
  changDDrs: function () {
    this.setData({ showDDrs: true });
  },
  // // 配送方编辑
  // changPsUsage: function () {
  //   this.setData({ showPSF: true });
  // },
  //配送时间编辑
  changPsTime: function () {
    if (this.data.deliveryMethodArray.length == 1) {
      var type = this.data.deliveryMethodArray[0];
      if (type == 1)
        return;
    }
    this.setData({ showSCSJ: true });
  },
  // 到店时间编辑
  changDDdate: function () {
    this.setData({ showDDSJ: true });
  },

  // 外卖配送方式改变
  changPsfs: function (e) {
    if(this.data.deliveryMethodArray.length==1){
      return;
    }
    let type = e.currentTarget.dataset.type;//切换单选按钮
    this.setData({ deliveryMethod: type });
    this.getNetOrderInfo();//修改配送方式后，改变订单金额信息
  },

  // 弹出框控制
  onClose() {
    this.setData({
      showDDrs: false,
      // showPSF: false,
      showSCSJ: false,
      showDDSJ: false,
    });
  },
  // 到店人数确认
  onddrsConfirm(event) {
    const { picker, value, index } = event.detail;
    // Toast(`当前值：${value}, 当前索引：${index}`);
    this.setData({
      ddrsValue: value,
      showDDrs: false,
    });
  },
  // // 配送方编辑
  // onpsDwConfirm(event) {
  //   const { picker, value, index } = event.detail;
  //   // Toast(`当前值：${value}, 当前索引：${index}`);
  //   var that = this;
  //   this.setData({
  //     psDwValue: value,
  //     showPSF: false,
  //     psDwCode: that.data.psDwColumns[index].Id,
  //   });
  // },
  // 送出时间
  // onscTimeConfirm(event) {
  //   const { picker, value, index } = event.detail;
  //   // Toast(`当前值：${value}, 当前索引：${index}`);
  //   var that = this;
  //   this.setData({
  //     SCSJValue: value,
  //     showSCSJ: false,
  //     SCSJWZValue: that.data.sctimeWzColumns[index],
  //   });
  // },
  onscTimeConfirm(event) {
    if (event.detail<this.data.pssjminDate){
      wx.showToast({
        title: "不可小于最小配送时间",
        icon: 'none'
      })
      return;
    }
    this.setData({
      SCSJValue: timestampToYMD(event.detail, "M月D日 h:m"),
      SCSJWZValue: timestampToYMD(event.detail, "Y-M-D h:m:s"),
      pscurrentDate: event.detail,
      showSCSJ: false,
      deliveryMethod: 2
    });
    if (this.data.deliveryMethod == 2) {
      this.getNetOrderInfo();//修改配送方式后，改变订单金额信息
    }
  },
  //到店时间确定
  onddsjConfirm(event) {
    this.setData({
      ddsjCurrentDate: timestampToYMD(event.detail, "Y/M/D h:m"),
      showDDSJ: false,
    });
  },

  //网络请求
  //获取订单配置信息
  getNetOrderInfoConfig: function () {
    var list = [];
    for (var gindex in this.data.goodsList) {
      var gmodel = this.data.goodsList[gindex];
      var model = new Object();
      model.ProductCode = gmodel.ProductCode;
      model.Count = gmodel.amount;
      list.push(model);
    }
    var that = this;
    HTTP({
      url: URL.order.getOrderMainConfig,
      userToken: getUserToken(),
      data: {
        ProductList: list,
        MemberId: getUserInfo().memberId,
      },
      success: (ress) => {
        wx.hideLoading();
        var res = ress.Data;
        var defDeliveryMethod=0;
        if (res.DeliveryMethod.length==1){
          defDeliveryMethod=res.DeliveryMethod[0];
        }
        that.setData({
          pssjminDate: res.LatestTimeTs * 1000,
          pscurrentDate: res.LatestTimeTs * 1000,
          SCSJValue: timestampToYMD(res.LatestTimeTs * 1000, "M月D日 h:m"),
          SCSJWZValue: timestampToYMD(res.LatestTimeTs * 1000,"Y-M-D h:m:s"),
          deliveryMethod: defDeliveryMethod,
          deliveryMethodArray: res.DeliveryMethod,
        });
        that.getNetOrderInfo();
      },
      fail: (res) => {
        wx.hideLoading();
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //获取订单价格信息
  getNetOrderInfo: function () {
    var list = [];
    for (var gindex in this.data.goodsList) {
      var gmodel = this.data.goodsList[gindex];
      var model = new Object();
      model.ProductCode = gmodel.ProductCode;
      model.Count = gmodel.amount;
      list.push(model);
    }
    var storeId = "";
    if (this.data.storeInfo) {
      storeId = this.data.storeInfo.StoreId;
    }
    var addressCode = this.data.addressInfo ? this.data.addressInfo.AddressCode:"";
    var deliveryMethod = parseInt(this.data.deliveryMethod)
    var usageModeltj = parseInt(this.data.usageModel) + 1;
    var that = this;
    HTTP({
      url: URL.order.getOrderMain,
      userToken: getUserToken(),
      data: {
        ProductList: list,
        MemberId: getUserInfo().memberId,
        StoreId: storeId,
        CouponCode: that.data.couponCode,
        DeliveryMethod: deliveryMethod,// 配送方式 1 正常配送 2 预约配送
        AddressCode: addressCode,
        DeliveryWay: usageModeltj,
        DeliveryTime: that.data.usageModel == 0 ? that.data.SCSJWZValue : that.data.ddsjCurrentDate
      },
      success: (ress) => {
        wx.hideLoading();
        var res = ress.Data;
        var listOther = [];
        for (var i in that.data.otherData) {
          var model = that.data.otherData[i];
          if (i == 0) {
            model.money = res.SoldTotalPrice;
          } else if (i == 1) {
            model.money = res.PackPrice;
          } else {
            model.money = res.DeliveryPrice;
          }
          listOther.push(model);
        }
        that.setData({
          otherData: listOther,
          totalPrice: res.SoldDiscountPrice,
          couponPrice: res.CouponPrice,
        })
      },
      fail: (res) => {
        wx.hideLoading();
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  // //获取配送方列表
  // getNetDeliveryList: function () {
  //   var that = this;
  //   HTTP({
  //     url: URL.order.getConfig,
  //     userToken: getUserToken(),
  //     data: {
  //       TypeCode: ["DeliveryThirdParty"],
  //       MemberId: getUserInfo().memberId,
  //     },
  //     success: (ress) => {
  //       wx.hideLoading();
  //       var res = ress.Data;
  //       var list = [];
  //       for (var i in res) {
  //         var model = res[i];
  //         list.push(model.SettingName);
  //       }
  //       if (res.length > 0) {
  //         that.setData({
  //           psDwColumns: res,
  //           psDwValue: res[0].SettingName,
  //           psDwValueColumns: list,
  //           psDwCode: res[0].Id,
  //         })
  //       }
  //     },
  //     fail: (res) => {
  //       console.log(res)
  //       wx.showToast({
  //         title: res.msg,
  //         icon: 'none'
  //       })
  //     }
  //   })
  // },
  //获取默认收获地址
  getNetDefAddressList: function () {
    var that = this;
    HTTP({
      url: URL.address.defaultAddressList,
      userToken: getUserToken(),
      data: {
        MemberId: getUserInfo().memberId,
      },
      success: (ress) => {
        var res = ress.Data;
        if (res.AddressInfos.length > 0) {
          that.setData({
            addressInfo: res.AddressInfos[0],
          })
        }
        that.getNetOrderInfoConfig();//获取订单信息
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        that.getNetOrderInfoConfig();//获取订单信息
      }
    })
  },
  //获取默认门店
  getNetDefStoreList: function () {
    wx.showLoading({
      title: '加载中...'
    })
    var that = this;
    HTTP({
      url: URL.order.getDefaultStoreList,
      userToken: getUserToken(),
      data: {
        ProductCode: that.data.goodsList[0].ProductCode,
        MemberId: getUserInfo().memberId,
      },
      success: (ress) => {
        var res = ress.Data;
        if (res.StoreInfos.length > 0) {
          that.setData({
            storeInfo: res.StoreInfos[0],
          })
        }
        that.getNetDefAddressList();//获取默认收获地址
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //提交订单
  submitOrder: function () {
    if (!this.data.addressInfo) {
      wx.showToast({
        icon: 'none',
        title: '请先设置地址'
      })
      return;
    }
    if (this.data.usageModel==0&&this.data.deliveryMethod==0) {
      wx.showToast({
        icon: 'none',
        title: '请先选择配送方式'
      })
      return;
    }
    wx.showLoading({
      title: '订单提交中...'
    })
    var list = [];
    for (var gindex in this.data.goodsList) {
      var gmodel = this.data.goodsList[gindex];
      var model = new Object();
      model.ProductCode = gmodel.ProductCode;
      model.Count = gmodel.amount;
      list.push(model);
    }
    var that = this;
    var storeId = "";
    if (that.data.storeInfo) {
      storeId = that.data.storeInfo.StoreId;
    }
    var deliveryMethod =parseInt(this.data.deliveryMethod) // 配送方式 1 正常配送 2 预约配送
    var usageModeltj = parseInt(this.data.usageModel) + 1;
    HTTP({
      url: URL.order.createOrder,
      userToken: getUserToken(),
      data: {
        ProductList: list,
        MemberId: getUserInfo().memberId,
        CouponCode: that.data.couponCode,
        AddressCode: that.data.addressInfo.AddressCode,
        StoreId: storeId,
        DeliveryWay: usageModeltj,
        DeliveryTime: that.data.usageModel == 0 ? that.data.SCSJWZValue : that.data.ddsjCurrentDate,
        // DeliveryThirdParty: that.data.psDwCode,
        PersonCount: that.data.ddrsValue,
        Remark: that.data.remarkCon == _("设置备注") ? "" : that.data.remarkCon,
        InvoiceCode: that.data.fapiaoModel ? that.data.fapiaoModel.InvoiceCode : "",
        DeliveryMethod: deliveryMethod
      },
      success: (ress) => {
        var res = ress.Data;
        wx.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.package,
          signType: res.signType,
          paySign: res.paySign,
          success: function (res) {
            //支付成功
            wx.showToast({
              title: _('支付成功'),
              icon: 'succes',
              duration: 1000,
              mask: true
            })
            getApp().globalData.isShuaxinHome = true;
            setTimeout(function () {
              //你需要执行的代码
              wx.switchTab({
                url: PAGES.mainPage,
              });
            }, 1000)
          },
          fail: function (res) {
            console.log("hlwfail:" + res.data)
            wx.showToast({
              title: _('支付失败'),
              icon: 'none'
            })
            getApp().globalData.isShuaxinHome=true;
            setTimeout(function () {
              //你需要执行的代码
              wx.switchTab({
                url: PAGES.mainPage,
              });
            }, 1000)
          }
        })
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },

})